import { defineComponent, reactive, onMounted, watch, markRaw, nextTick } from 'vue'
import * as echarts from 'echarts'
import styles from '../../index.module.scss'
import type { DimMatrixChartDataListType } from './typings'

export default defineComponent({
  name: 'DimLineChart1',
  props: ['dataList', 'id'],
  setup(
    props: { dataList: any; id: string } = {
      dataList: [],
      id: 'contents'
    }
  ) {
    const state = reactive<DimMatrixChartDataListType>({
      dataset: {
        source: []
      }
    })
    watch(
      () => props.dataList,
      () => {
        lineInit()
      }
    )

    onMounted(() => {
      nextTick(() => {
        createLineInit()
      })
    })

    // methods
    // 初始化echarts实例
    const createLineInit = () => {
      const dom = document.getElementById(props.id)
      state.myChart = markRaw(echarts.init(dom!))
      lineInit()
    }

    // 绘图
    const lineInit = () => {
      // 绘制图表
      state.myChart.clear()
      state.myChart.setOption({
        title: {
          text: '当日灯杆24小时能耗曲线图',
          right: 16
        },
        color: ['#c4a6ff', '#1cebd4', '#65afff'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line'
          },
          formatter: function (param: any) {
            let barFormatter = `<div style='color: #333;'>${param[0].name}时</div>`
            for (let i = 0; i < param.length; i++) {
              barFormatter += `<div style='color: #666;'>${param[i].marker} ${param[i].seriesName}：${param[i].value}</div>`
            }
            return barFormatter
          },
          confine: true // 提示框 不限制必须在框内
        },
        legend: {
          data: ['额定功率', '实际功率'],
          left: 10
        },
        xAxis: {
          type: 'category',
          data: props.dataList?.hour
        },
        yAxis: [
          {
            name: '额定功率',
            type: 'value',
            position: 'left'
          },
          {
            name: '实际功率',
            type: 'value'
          }
        ],
        series: [
          {
            name: '额定功率',
            type: 'line',
            yAxisIndex: 0,
            data: props.dataList?.ratedEnergy
          },
          {
            name: '实际功率',
            type: 'line',
            yAxisIndex: 1,
            data: props.dataList?.realEnergy
          }
        ]
      })

      // 建议加上以下这一行代码，不加的话，当浏览器窗口缩小时，超过div界限
      window.addEventListener('resize', function () {
        state.myChart.resize()
      })
    }

    return () => (
      <div class={styles['line-chart']}>
        <div id={props.id} class={styles['statistics-map']}></div>
      </div>
    )
  }
})
